﻿using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;

namespace Longbow.Web
{
    /// <summary>
    ///
    /// </summary>
    internal class DefaultIPLocator : IIPLocator
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public virtual string Locate(IPLocatorOption option) => string.Empty;

        /// <summary>
        ///
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        protected string Locate<T>(IPLocatorOption option) where T : class
        {
            var ret = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(option.Url) && option.HttpClient != null)
                {
                    var task = option.HttpClient.GetAsJsonAsync<T>(option.Url);
                    task.Wait(option.RequestTimeout);
                    if (task.IsCompleted && !task.IsFaulted && task.Result != null) ret = task.Result.ToString() ?? string.Empty;
                }
            }
            catch (Exception ex)
            {
                option.Logger.LogError(ex, option.Url);
            }
            return ret;
        }
    }
}
